package com.dfl.ggbond.media;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//统一加载器
public class MediaLoad {
    //创建线程池
    private static final ExecutorService excutor = Executors.newSingleThreadExecutor();

    //Picture
    public static void asyncLoadPicture(Context context, int pageIndex, int pageSize, MediaDataCallback callback) {
        excutor.execute(() -> {
            List<MediaInfo> list = new ArrayList<>();
            Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            //获取字段
            String[] protection;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//高版本没有DATA路径
                protection = new String[]{
                        MediaStore.Images.Media._ID,
                        MediaStore.Images.Media.DISPLAY_NAME,
                        MediaStore.Images.Media.SIZE,
                        MediaStore.Images.Media.DATE_ADDED,
                        MediaStore.Images.Media.DATE_MODIFIED,
                        MediaStore.Images.Media.MIME_TYPE,
                        MediaStore.Images.Media.WIDTH,
                        MediaStore.Images.Media.HEIGHT
                };
            } else {            //低版本直接访问DATA
                protection = new String[]{
                        MediaStore.Images.Media._ID,
                        MediaStore.Images.Media.DISPLAY_NAME,
                        MediaStore.Images.Media.DATA,   //文件路径
                        MediaStore.Images.Media.SIZE,
                        MediaStore.Images.Media.DATE_ADDED,
                        MediaStore.Images.Media.DATE_MODIFIED,
                        MediaStore.Images.Media.MIME_TYPE,
                };
            }

            String sortOrder = MediaStore.Images.Media.DATE_ADDED + " DESC";//按添加时间倒序
            //查询媒体库数据
            try (Cursor cursor = context.getContentResolver().query(uri, protection, null, null, sortOrder);) {
                if (cursor != null && cursor.moveToPosition(pageIndex * pageSize)) {
                    int count = 0;
                    do {
                        // 每次处理一条数据
                        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                        String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
                        long size = getLongSafely(cursor, MediaStore.Images.Media.SIZE);
                        long dateAdded = getLongSafely(cursor, MediaStore.Images.Media.DATE_ADDED);
                        long dateModified = getLongSafely(cursor, MediaStore.Images.Media.DATE_MODIFIED);
                        String mime = getStringSafely(cursor, MediaStore.Images.Media.MIME_TYPE);

                        String path = "";
                        Integer width = null, height = null;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            // 高版本没有DATA字段，用content uri表示
                            path = ContentUris.withAppendedId(uri, id).toString();
                            width = getIntSafely(cursor, MediaStore.Images.Media.WIDTH);
                            height = getIntSafely(cursor, MediaStore.Images.Media.HEIGHT);
                        } else {
                            // 低版本有DATA字段
                            path = String.valueOf(getLongSafely(cursor, MediaStore.Images.Media.DATA));
                        }
                        Uri contentUri = ContentUris.withAppendedId(uri, id);
                        MediaInfo info = new MediaInfo(
                                id,
                                name != null ? name : "",
                                path != null ? path : "",
                                contentUri,
                                size,
                                dateAdded,
                                dateModified,
                                mime != null ? mime : "",
                                width,
                                height,
                                null, // duration 音视频时长，这里图片为null
                                null, // artist 音乐作者，这里图片为null
                                null  // album  音乐专辑，这里图片为null
                        );
                    list.add(info);
                    count++;
                    // 达到分页数量就退出
                    if (count >= pageSize) break;
                } while (cursor.moveToNext());
            }
            // 查询完毕，回调返回结果
            if (callback != null) callback.onLoadComplete(list);
        } catch (Exception e) {
                // 出错时回调错误
                if (callback != null) callback.onLoadError(e);
            }
        });
    }

    // 回调接口
    public interface MediaDataCallback {
        void onLoadComplete(List<MediaInfo> list);
        void onLoadError(Exception e);
    }

    //安全获取Long字段
    private static long getLongSafely(Cursor cursor, String column) {
        int idx = cursor.getColumnIndex(column);
        if (idx != -1 && !cursor.isNull(idx)) return cursor.getLong(idx);
        return 0L;
    }

    //安全获取String字段
    private static String getStringSafely(Cursor cursor, String column) {
        int idx = cursor.getColumnIndex(column);
        if (idx != -1 && !cursor.isNull(idx)) return cursor.getString(idx);
        return "";
    }

    //安全获取int字段
    private static Integer getIntSafely(Cursor cursor, String column) {
        int idx = cursor.getColumnIndex(column);
        if (idx != -1 && !cursor.isNull(idx)) return cursor.getInt(idx);
        return null;
    }
}